'''
Created on Aug 2, 2012

@author: loic
'''

import os, sys, csv, shutil, random, sqlite3
from subprocess import Popen,PIPE

maxsize = 8000000
filename = '/home/loic/mp3list1.csv'
dest = '/media/PUBLIC'
fields = ['dir', 'concat', 'size', 'new', 'new_old', 'old', 'split', 'select']

class liste():
    def __init__(self, name):
        self.data = []
        self.indexes = []
        self.index = 0
        self.name = name
    def add_from_sql(self, cursor, sql):
        cursor.execute(sql)
        for row in cursor:
            self.append(row)
    def append(self, d):
        self.data.append(d)
        self.indexes.append(self.index)
        self.index += 1
    def random(self):
        if len(self.indexes) == 0:
            print 'Resetting list %s' % self.name
            self.index = 0
            for i in self.data:
                self.indexes.append(self.index)
                self.index += 1
        choice = random.choice(self.indexes)
#        print "%\t%schoice
#        self.data[choice]['select'] = 'X'
        self.indexes.remove(choice)
        return self.data[choice]
    def lenght(self):
        return len(self.data)
    def __str__(self):
        return self.data.__str__()
    def __getitem__(self, i):
        return self.data[i]
    def __len__(self):
        return len(self.data)
    
class types():
    def __init__(self, new, new_old, old, best, not_orig):
        self.types = ['new', 'new_old', 'new', 'old']
        self.index = 0
        self.data = {}
        self.data['new'] = new
        self.data['new_old'] = new_old
        self.data['old'] = old
    def next(self):
        idx = self.types[self.index]
        val = self.data[idx].random()
        self.index += 1
        if self.index == len(self.types): self.index = 0
        return (val, idx)

new = liste('new');
new_old = liste('new_old');
old = liste('old');
split = liste('split');
best = liste('best');
not_orig = liste('not_orig');

def make_playlist_sq():
    conn = sqlite3.connect('/home/loic/mp3.sqlite')
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    new.add_from_sql(c, 'select * from folders where new')
    new_old.add_from_sql(c, 'select * from folders where new_old')
    old.add_from_sql(c, 'select * from folders where old')
    best.add_from_sql(c, 'select * from folders where best')
    not_orig.add_from_sql(c, 'select * from folders where not_orig')
        
    playlist = []
   
    size=0
    n = 1
    t = types(new, new_old, old, best, not_orig)
    for i in range(new.lenght()):
        sel = new.random()
        playlist.append(sel)
        c.execute('insert into playlist values(?, ?, ?)', (n, sel['concat'], 'new'))
        size += int(sel['size'])
        n += 1
        print "%2d (%d)\t%s" % (n, size, sel['concat'])
    conn.commit()
    while size < maxsize:
        (sel, type) = t.next()
        playlist.append(sel)
        c.execute('insert into playlist values(?, ?, ?)', (n, sel['concat'], type))
        conn.commit()
        size += int(sel['size'])
        n += 1
        print "%2d (%d)\t%s" % (n, size, sel['concat'])
    c.close()
    
def make_playlist():
    new = liste();
    new_old = liste();
    old = liste();
    split = liste();
    select = liste();
    nowhere = liste();
    
    playlist = []
   
    reader = csv.DictReader(open(filename, 'r'), dialect=csv.excel)
    for d in reader:
#        print d
        if d['select'] != '':
#            print "-->select : %s" % d['select']
            select.append(d)
        elif d['old'] != '':
#            print "-->old : %s" % d['old']
            old.append(d)
        elif d['new_old'] != '':
            new_old.append(d)
        elif d['new'] != '':
            new.append(d)
        elif d['split'] != '':
            split.append(d)
        else:
            nowhere.append(d)
#        print "select: %d, old: %d, new_old: %d, new: %d, split: %d, : %d"  % (len(select),len(old),len(new_old),len(new),len(split),len(nowhere))
#    print new[0]
    size=0
    n = 1
    t = types(new, new_old, old)
    for i in range(new.lenght()):
        sel = new.random()
        playlist.append(sel)
        size += int(sel['size'])
        n += 1
        print "%2d (%d)\t%s" % (n, size, sel['concat'])
    while size < maxsize:
        sel = t.next()
        playlist.append(sel)
        size += int(sel['size'])
        n += 1
        print "%2d (%d)\t%s" % (n, size, sel['concat'])
        
#    print playlist


def copyPL():
    global dest
    reader=csv.reader(open('/home/loic/playlist.csv', 'r'), dialect=csv.excel_tab)
    i = 1
    for row in reader:
        print 'copying %s' % row[0],
        name = '%s/%03d_%s' % (dest, i, row[1])
        i += 1
        print ' to %s' % name
        try:
            shutil.copytree(row[0], name)
        except:
            pass
    
if __name__ == '__main__':
    make_playlist_sq()
